package org.test.interceptor;

import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.test.dto.JsonMessage;

import com.fasterxml.jackson.databind.ObjectMapper;

@Component
public class XSSInterceptor implements HandlerInterceptor {
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		Map<String, String[]> dataMap = request.getParameterMap(); 
		// 遍历集合
		for (String[] dataArr : dataMap.values()) {
			for (int i = 0; i < dataArr.length; i++) {
				String data = dataArr[i];
				// 判断是否包含非法字符
				if (data.indexOf("<") != -1 || data.indexOf(">") != -1) {
					// 可能包含非法字符	
					if(data.indexOf("script") != -1 ||data.indexOf("input") != -1 ||data.indexOf("textarea") != -1||
							data.indexOf("button") != -1||data.indexOf("img") != -1 || data.indexOf("a") != -1 ||
							data.indexOf("video") != -1 ||data.indexOf("link") != -1 ||data.indexOf("ul") != -1 ||
							data.indexOf("select") != -1||data.indexOf("option") != -1||data.indexOf("li") != -1) {
						// 含有非法字符
						JsonMessage msg = new JsonMessage();
						msg.setId(1);
						msg.setMsg("含有非法字符！");
						ObjectMapper mapper = new ObjectMapper();
						String json = mapper.writeValueAsString(msg);
						response.setCharacterEncoding("utf-8");
						PrintWriter writer = response.getWriter();
						writer.print(json);
						writer.flush();
						writer.close();
						return false;
						
					}
				}

			}
		}
		return HandlerInterceptor.super.preHandle(request, response, handler);
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		HandlerInterceptor.super.afterCompletion(request, response, handler, ex);

	}

}
